<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

	<meta http-equiv="X-UA-Compatible" content="IE=edge">

	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">

	<meta name="author" content="PIXINVENT">

	<title>749便利店管理系統</title>

	<link rel="stylesheet" type="text/css" href="app-assets/css/vendors.css">

	<link rel="stylesheet" type="text/css" href="app-assets/css/vertical-menu.css">

	<link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap-extended.css">

	<!-- 引入 SweetAlert2 的 CSS -->
	<link rel="stylesheet" href="date/css/sweetalert2.min.css">

</head>

<body>

	<div class="content-wrapper">

		<div class="content-header">

			<div class="content-header-left mb-2 clearfix">

				<h3 class="content-header-title mb-0">采购订单</h3>

			</div>

		</div>

		<div class="card">

			<div class="card-content">

				<div class="card-body">

					<div class="table-responsive">

						<table class="table">

							<thead>

								<tr>

									<th>订单ID</th>

									<th>总金额</th>

									<th>订单日期</th>

									<th>订单状态</th>

									<th>操作</th>

								</tr>

							</thead>

							<tbody id="showOrder">

								<!-- 表格行 1 -->

							</tbody>

						</table>

						<div class="page clearfix">

							<div class="pull-left">共 <span id="total"></span> 条记录 第 <span id="pageNum"></span> / <span
									id="pages"></span> 页

							</div>

							<div class="pull-right">

								<nav aria-label="..." class="pull-left">

									<ul class="pagination" id="pageTo">

									</ul>

								</nav>

							</div>

						</div>

					</div>

				</div>

			</div>

		</div>

	</div>


	<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle"
		aria-hidden="true">
		<div class="modal-dialog modal-lg" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLongTitle">订单详情</h5>
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
				</div>
				<div class="modal-body">
					<table class="table">
						<thead>
							<tr>
								<th>商品名称</th>
								<th>商品品牌</th>
								<th>商品售价</th>
								<th>商品采购价</th>
								<th>商品数量</th>
								<th>小计</th>
								<th>描述</th>
							</tr>
						</thead>
						<tbody id="showSupplierAndProductMessage">
							<!-- 数据将动态加载到此处 -->
						</tbody>
					</table>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
				</div>
			</div>
		</div>
	</div>
	</div>

	<script src="app-assets/js/vendors.min.js" type="text/javascript"></script>

	<script src="app-assets/js/app-menu.js" type="text/javascript"></script>

	<script src="app-assets/js/app.js" type="text/javascript"></script>

	<script src="app-assets/js/echarts.min.js" type="text/javascript"></script>

	<script src="app-assets/js/sweetalert2.js" type="text/javascript"></script>


	<!-- 引入 SweetAlert2 的 JS -->
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18/dist/sweetalert2.all.min.js"></script>

</body>

<script>
	const HTTPUrL='http://localhost:25080'; 
	const orderQuery={
		'pageNum': 1,
		'pageSize': 5,
		'orderId':'',
		'status':'',
	}
	// 初始化所有订单
	function selectAll(pageNum) {
		orderQuery.pageNum = pageNum;
		$.ajax({

			'url': HTTPUrL + '/purchaseOrders/page',

			'type': 'post',

			'dataType': 'json',
			'contentType': 'application/json',
			'data': JSON.stringify(orderQuery),

			'success': selectAllSuccess

		})
	}

	//定义格式化日期函数

	function formatDate(date) {

		var d = new Date(date),

			month = '' + (d.getMonth() + 1),

			day = '' + d.getDate(),

			year = d.getFullYear();

		if (month.length < 2)

			month = '0' + month;

		if (day.length < 2)

			day = '0' + day;

		return [year, month, day].join('-');

	}

	// 成功回调函数 显示订单
	function selectAllSuccess(data) {
		$('#showOrder tr').remove();

		data.data.list.forEach(dd => {
			// 根据订单状态决定是否显示收货按钮
			let receiveButton = '';
			if (dd.status == '2') {
				receiveButton = `<button class="btn btn-sm btn-success" onclick="shouhuo('${dd.orderId}')">收货</button>`;
			}

			// 动态设置状态颜色
			let color = '';
			switch (dd.status) {
				case 0:
				color = 'red'; // 红色
					break;
				case 1:
				color = 'blue'; // 蓝色
					break;
				case 2:
				color = 'green'; // 绿色
					break;
				default:
				color = 'orange'; //橘色
					break;
			}

			$('#showOrder').append(`
            <tr id="order-${dd.orderId}">
                <td>${dd.orderId}</td>
                <td>￥${parseFloat(dd.totalAmount).toFixed(2)}</td>
                <td>${formatDate(dd.orderDate)}</td>
                <td style = 'color: `+color+`'>${dd.status == '0' ? '待发货' : dd.status == '1' ? '发货中' : dd.status == 4  ? '已完结' : '其他'}</td>
                <td>
                    <button class="btn btn-sm btn-primary" data-toggle="collapse" data-target="#divOrderMessages-${dd.orderId}">
                        <i class="fas fa-chevron-down"></i> 查看详情
                    </button>
                </td>
            </tr>
            <tr>
                <td colspan="5">
                    <div id="divOrderMessages-${dd.orderId}" class="collapse">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>订单ID</th>
                                    <th>供应商名称</th>
                                    <th>小计</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                    <th>详情</th>
                                </tr>
                            </thead>
                            <tbody id="showMessages-${dd.orderId}">
                            </tbody>
                        </table>
                    </div>
                </td>
            </tr>`);

			// 子订单信息展示
			dd.childOrderList.forEach((subOrder) => {
				let operationButton = '';
				if (subOrder.status == '0') {
					operationButton = `<button class="btn btn-sm btn-success ship-btn" onclick="shipOrder('${subOrder.orderId}', '${subOrder.supplierId}')">发货</button>`;
				} else if (subOrder.status == '1') {
					operationButton = `
					<button class="btn btn-sm btn-info receive-btn" onclick="receiveOrder('${subOrder.orderId}', '${subOrder.supplierId}')">收货</button>
					<button class="btn btn-sm btn-info receive-btn" onclick="returnGoods('${subOrder.orderId}', '${subOrder.supplierId}')">退货</button>					
					`;
				}

				// 动态设置子订单状态颜色
				let color = '';
			switch (subOrder.status) {
				case 0:
				color = 'red'; // 红色
					break;
				case 1:
				color = 'blue'; // 蓝色
					break;
				case 2:
				color = 'green'; // 绿色
					break;
				default:
				color = 'orange'; //橘色
					break;
			}

				$('#showMessages-' + subOrder.orderId).append(`
                <tr id="orderMessages-${subOrder.orderId}">
                    <td>${subOrder.orderId}</td>
                    <td>${subOrder.supplierName}</td>
                    <td>￥${parseFloat(subOrder.totalAmount).toFixed(2)}</td>
                    <td style = 'color: `+color+`'>${subOrder.status == '0' ? '待发货' : subOrder.status == '1' ? '已发货' : subOrder.status == '2' ? '已收货' : subOrder.status == '3' ? '已退货' : '其他'}</td>
                    <td>${operationButton}</td>
                    <td><button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#exampleModalLong" onclick="xq('${subOrder.orderId}', '${subOrder.supplierId}')">订单详情</button></td>
                </tr>`);
			});
		});

		// 更新分页信息
		$('#total').text(data.data.total); // 总记录数
		$('#pageNum').text(data.data.pageNum); // 当前页码
		$('#pages').text(data.data.pages); // 总页数

		// 渲染分页按钮
		renderPagination(data.data);
	}


	// 发货操作
	function shipOrder(orderId, supplierId) {
		Swal.fire({
			title: '确认发货?',
			text: "您确定要发货吗?",
			icon: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: '确认发货'
		}).then((result) => {
			if (result.isConfirmed) {
				$.ajax({
					'url': HTTPUrL + '/purchaseOrders/updateStatus/'+orderId+'/'+supplierId,
					'type': 'get',
					'dataType': 'json',
					'success': function (response) {
						console.log(response);
						if (response.code == 200) {
							Swal.fire({
								title: '发货成功!',
								text: '订单已成功发货。',
								icon: 'success',
								confirmButtonText: '确认'
							}).then((result) => {
								if (result.isConfirmed) {
									// 用户点击了确认按钮
									window.location.reload(); // 刷新页面
								}
							})
						} else {
							Swal.fire('发货失败!', response.message, 'error');
						}
					}
				});
			}
		});
	}
	function returnGoods(orderId, supplierId) { 
		Swal.fire({
			title: '确认退货?',
			text: "您确定要退货吗?",
			icon: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: '确认退货'
		}).then((result) => {
			if (result.isConfirmed) {
				$.ajax({
					'url': HTTPUrL + '/purchaseOrders/returnGoods/'+orderId+'/'+supplierId,
					'type': 'get',
					'dataType': 'json',
					'success': function (response) {
						console.log(response);
						if (response.code == 200) {
							Swal.fire({
								title: '退货成功!',
								text: '订单已成功退货。',
								icon: 'success',
								confirmButtonText: '确认'
							}).then((result) => {
								if (result.isConfirmed) {
									// 用户点击了确认按钮
									window.location.reload(); // 刷新页面
								}
							})
						} else {
							Swal.fire('退货失败!', response.message, 'error');
						}
					}
				});
			}
		});
	}





	// 收货操作
	function receiveOrder(orderId, supplierId) {
		Swal.fire({
			title: '确认收货?',
			text: "您确定要收货吗?",
			icon: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#3085d6',
			cancelButtonColor: '#d33',
			confirmButtonText: '确认收货'
		}).then((result) => {
			if (result.isConfirmed) {
				$.ajax({
					'url': HTTPUrL + '/purchaseOrders/receive/'+orderId+'/'+supplierId,
					'type': 'get',
					'dataType': 'json',
					'success': function (response) {
						if (response.code == 200) {
							Swal.fire({
								title: '收货成功!',
								text: '订单已成功收货。',
								icon: 'success',
								confirmButtonText: '确认'
							}).then((result) => {
								if (result.isConfirmed) {
									// 用户点击了确认按钮
									window.location.reload(); // 刷新页面
								}
							})
						} else {
							Swal.fire('发货失败!', response.message, 'error');
						}
					},
					'error': function (jqXHR, textStatus, errorThrown) {
						Swal.fire('收货失败!', '服务器错误: ' + textStatus, 'error');
					}
				});
			}
		});
	}

	//渲染分页
	function renderPagination(data) {

		const pagination = $('#pageTo');

		pagination.empty();

		for (let i = 1; i <= data.pages; i++) {

			pagination.append(`

            <li class="page-item ${i === data.pageNum ? 'active' : ''}">

                <a class="page-link" href="javascript:void(0);" onclick="selectPage(${i})">${i}</a>

            </li>

        `);

		}

	}

	// 分页查询
	function selectPage(pageNum) {

		selectAll(pageNum);

	}

	$(document).ready(function () {

		selectAll(1);

	});

	// 大订单修改收货
	function shouhuo(orderId) {
		// 获取订单状态
		const orderRow = $(`#order-${orderId}`);
		const statusText = orderRow.find('td:eq(3)').text(); // 获取状态列的文本
		const status = statusText === '已发货' ? '2' : statusText === '已收货' ? '3' : statusText;

		if (status == '0') {
			alert("该订单还未发货");
			return;
		} else if (status == '1') {
			alert("该订单正在发货中，请勿着急");
			return;
		} else if (status == '2') {
			Swal.fire({
				title: '确认收货?',
				text: "您确定要收货吗?",
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: '确认收货'
			}).then((result) => {
				if (result.isConfirmed) {
					$.ajax({
						url: HTTP.getUserInfo + 'purchaseOrders/updateStatusByOrderId',
						type: 'post',
						data: { orderId: orderId },
						success: function (response) {
							if (response.success) {
								Swal.fire('收货失败!', response.message, 'error');
							} else {

								Swal.fire('收货成功!', '订单已成功收货。', 'success').then(() => {
									// 刷新整个页面
									window.location.reload();
								});
							}
						},
						error: function (jqXHR, textStatus, errorThrown) {
							Swal.fire('收货失败!', '服务器错误: ' + textStatus, 'error');
						}
					});
				}
			});
		} else if (status == '3') {
			alert("该订单已经收货了");
			return;
		}
	}


	//点击详情

	function xq(orderId, supplierId) {
		// alert(orderId + supplierId)
		$.ajax({
			type: 'get',
			url: HTTPUrL+'/purchaseOrderDetails/selectOrderDetails/'+orderId+'/'+supplierId,
			success: function (data) {
				$('#showSupplierAndProductMessage').empty();
				console.log(data);
				var showProductAndPodMessage = data.data;
				showProductAndPodMessage.forEach(function (dd) {
					var str = `
					<tr>
						<td>${dd.productName}</td>
						<td>${dd.brand}</td>
						<td>${dd.price}</td>
						<td>${dd.unitPrice}</td>
						<td>${dd.quantity}</td>
						<td>${dd.subtotal}</td>
						<td>${dd.description}</td>
					</tr>
				`
					$('#showSupplierAndProductMessage').append(str);
				});
			}
		});
	}

</script>

</html>